class UsersController < ApplicationController
  before_filter :edit_own_profile, :only => [:edit, :update]
  before_filter :authorize, :except => [:new, :create] if Rule.registration_enable?

  def patient
    @users = User.find(:all, :conditions => ["role_id=?", Role.patient.id], :order => :firstname)
  end
  
  def not_patient
    @users = User.find(:all, :conditions => ["role_id!=?", Role.patient.id], :order => :firstname)
  end

  def index
    @users = User.find(:all, :order => :firstname)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @users }
    end
  end

  # GET /users/1
  # GET /users/1.xml
  def show
    @user = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @user }
    end
  end

  # GET /users/new
  # GET /users/new.xml
  def new
    @user = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user }
    end
  end

  # GET /users/1/edit
  def edit
    @user = User.find(params[:id])
  end

  # PUT /users/1
  # PUT /users/1.xml
  def update
    @user = User.find(params[:id])

    respond_to do |format|
      if @user.update_attributes(params[:user])
        flash[:notice] = "Utilisateur #{@user.firstname} mis à jour avec succès."
        format.html { redirect_to(@user) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # POST /users
  # POST /users.xml
  def create
    params[:user]["role_id"] = Role.user.id.to_s
    @user = User.new(params[:user])
    
    respond_to do |format|
      if @user.save
        flash[:notice] = "Utilisateur #{@user.firstname} créé avec succès."
        session[:user_id] = @user.id
        format.html { redirect_to :home  }
        format.xml  { render :xml => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  private
  def edit_own_profile
    unless session[:user_id].to_i == params[:id].to_i && User.find(session[:user_id]).role.id == Role.superadmin.id
      flash[:notice] = "Vous ne pouvez modifier que votre profil"
      redirect_to :action => :show, :id => params[:id]
    end
  end
end
